<template>
  <div
    class="gallery"
    @mouseleave="handleMouseLeave"
  >
    <div
      v-for="(item, index) in list"
      :key="index"
      class="img-wrapper"
      :class="{'img-wrapper__selected': index === selectedModel}"
      @mouseenter="handleMouseEnter(index)"
    >
      <el-image
        :src="item[srcKey]"
        :style="{width: width + 'px', height: height + 'px' }"
        v-bind="{...elImageProps}"
        :alt="item[altKey] ?? '图片'"
        @click="handleClick(index)"
      >
        <template #placeholder>
          <slot name="placeholder">
            <div class="image-slot">
              加载中<span class="dot">...</span>
            </div>
          </slot>
        </template>
      </el-image>
      
      <template v-if="!disableClose">
        <div
          v-if="isShowClose === index"
          class="delete-icon"
          @click.stop="close(item, index)"
        >
          <el-icon><Close /></el-icon>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
const props = withDefaults(defineProps<{
  list: any[];
  disableClose?: boolean;
  width?: number;
  height?: number;
  srcKey?: string;
  altKey?: string;
  elImageProps?: any;
  selectable?: boolean;
  selected?: number;
}>(), {
  srcKey: 'src',
  altKey: 'alt',
  width: 50,
  height: 50,
  elImageProps: {},
  disableClose: false,
  selectable: false,
  selected: -1,
})

const emits = defineEmits<{
  (e: "close", { item, index }: {item: any, index: number}): void;
  (e: "update:selected", value: number): void;
}>()

const close = (item: any, index: number) => {
  emits("close", { item, index })
}

const isShowClose = ref(-1);
const handleMouseEnter = (index: number) => {
  isShowClose.value = index;
}

const handleMouseLeave = () => {
  isShowClose.value = -1;
}

const selectedModel = computed({
  get() {
    return props.selectable ? props.selected : -1
  },
  set(val: number) {
    emits("update:selected", val)
  }
})
const handleClick = (index: number) => {
  if (!props.selectable) {
    return
  }
  selectedModel.value = index
}
</script>

<style scoped lang="scss">
.gallery {
  width: 100%;
  display: flex;
  align-items: center;
  
  .img-wrapper {
    // display: inline-block;
    display: flex;
    position: relative;
  }
  
  .img-wrapper:not(:last-child) {
    margin-right: 5px;
  }

  .img-wrapper__selected {
    background: #F0F0F0;
  }
  
  .delete-icon {
    position: absolute;
    top: 0;
    right: 0;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 0, 0.2);
    cursor: pointer;
    color: white;
  }
  
  .delete-icon:hover {
    color: var(--el-color-danger);
  }

  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 14px;
  }
}
</style>